import os
import pandas as pd

print("start processing test results")
# 创建一个字典来统计每个 `a` 部分出现的次数

def process_txt_file(file_path, test_name):
    data = []
    with open(file_path, 'r', errors='ignore') as file:
        lines = file.readlines()
        status = 'ok'

        if lines[-1].startswith("not"):
            status = 'not ok'

        # 获取最后一行的内容
        last_line = lines[-1].strip()
        # detail 包含最后一行之前的所有内容
        if status == 'not ok' and '#' in last_line:
         error_detail = last_line.split('#', 1)[1].strip()  # 获取#后面的内容
         # 将其格式化为红色字体
         # detail 包含最后一行之前的所有内容，并将红色错误信息放到第一行
         detail = error_detail+"\n" + ''.join([line.strip() + "\n" for line in lines])
        else:
         # 如果是 ok，直接合并所有行
         detail =''.join([line.strip() + "\n" for line in lines]) 
        data.append([test_name, status, detail])
        return data
                    

def main(input_directory, output_file):
    all_data = []
    for file_name in os.listdir(input_directory):
        if file_name.endswith('.txt'):
            parts=file_name.split('.',1)
            file_path = os.path.join(input_directory, file_name)
            file_data = process_txt_file(file_path,parts[0])
            if file_data:
                for i in range(len(file_data)):
                    all_data.append(file_data[i])
    # Create a DataFrame
    columns = ['Test Name','Status','Run Details']
    df = pd.DataFrame(all_data, columns=columns)

    # Write DataFrame to an Excel file
    df.to_excel(output_file, index=False)
    print("success save test results to test_result.xlsx")
if __name__ == "__main__":
    input_directory = 'test'  # Change to your directory
    output_file = 'test_result.xlsx'
    main(input_directory, output_file)





